<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /* 
           preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
                                               [9]  [15,20,7]
                                              前序对应的是[20,15,7] 所以根节点是20
            //注意啊，leedcode必须return null 虽然不知道为啥
            */
            var buildTree = function (preorder, inorder) {
                if (!preorder.length) return null
                let root = {
                    val: preorder[0],
                    left: null,
                    right: null,
                }
                let mid = inorder.indexOf(root.val) //根节点是3  mid+1  所以对应的前序应该是[9]  [20,15,7]
                root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid))
                root.right = buildTree(preorder.slice(mid + 1), inorder.slice(mid + 1))
                return root
            }
            console.log(buildTree([3, 9, 20, 15, 7], [9, 3, 15, 20, 7]))
        </script>
    </body>
</html>
